package com.clientmanage.service.impl;

import com.clientmanage.domain.bean.ServiceItem;
import com.clientmanage.domain.vo.serviceItemVo;
import com.clientmanage.domain.resp.PageResult;
import com.clientmanage.mapper.ServiceItemMapper;
import com.clientmanage.service.IServiceItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HUANG
 * @since 2025-06-30
 */
@Service
public class ServiceItemServiceImpl extends ServiceImpl<ServiceItemMapper, ServiceItem> implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;

    /**
     * 分页模糊查询服务项目
     */
    @Override
    public PageResult<serviceItemVo> pageQuery(String name, String category, Boolean enabled, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<serviceItemVo> list = serviceItemMapper.selectPageVo(name, category, enabled, pageSize, offset);
        return new PageResult<>((long) pageSize, (long) pageNum, list, (long) list.size());
    }

    /**
     * 新增或更新服务项目
     */
    @Transactional
    @Override
    public void saveOrUpdateServiceItem(serviceItemVo vo) {
        ServiceItem entity = new ServiceItem();
        BeanUtils.copyProperties(vo, entity);
        // duration <-> durationMin 字段映射
        if (vo.getDuration() != null) {
            entity.setDurationMin(vo.getDuration());
        }
        if (vo.getId() == null) {
            entity.setCreatedAt(LocalDateTime.now());
            entity.setUpdatedAt(LocalDateTime.now());
            this.save(entity);
        } else {
            entity.setUpdatedAt(LocalDateTime.now());
            this.lambdaUpdate().eq(ServiceItem::getId, vo.getId()).update(entity);
        }
    }

    /**
     * 删除服务项目
     */
    @Transactional
    @Override
    public void deleteById(String id) {
        this.removeById(id);
    }
}
